<template>
	<!--  编辑弹框-->
	<el-dialog :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="35%">
		<template #header="{ titleId, titleClass }">
			<div class="my-header">
				<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
				<el-button type="danger" plain size="small" :icon="CircleCloseFilled" @click="handleClose"> 关闭弹框 </el-button>
			</div>
		</template>
		<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
			<el-form-item label="装备名称" prop="name">
				<el-input v-model="form.name" />
			</el-form-item>

			<el-form-item label="装备图片" prop="img">
				<el-upload action="" :before-upload="uploadimg" :show-file-list="true">
					<el-button type="primary" size="small">点击上传</el-button>
				</el-upload>
			</el-form-item>

			<el-form-item label="攻击力" prop="aggressivity">
				<el-input-number v-model="form.aggressivity" />
			</el-form-item>
			<el-form-item label="暴击率" prop="critical">
				<el-input-number v-model="form.critical" />
			</el-form-item>
			<el-form-item label="防御" prop="defense">
				<el-input-number v-model="form.defense" />
			</el-form-item>
			<el-form-item label="法力上限" prop="mana">
				<el-input-number v-model="form.mana" />
			</el-form-item>
			<el-form-item label="火焚耐性" prop="fire">
				<el-input-number v-model="form.fire" />
			</el-form-item>
			<el-form-item label="寒冻耐性" prop="ice">
				<el-input-number v-model="form.ice" />
			</el-form-item>
			<el-form-item label="毒伤耐性" prop="drug">
				<el-input-number v-model="form.drug" />
			</el-form-item>
			<el-form-item label="雷蛰耐性" prop="thunder">
				<el-input-number v-model="form.thunder" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
				<el-button type="primary" @click="handleSubmitForm(ruleFormRef)"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>

	<el-row style="width: 80%; margin: 0 auto; position: relative; top: 60px">
		<el-col>
			<el-form :inline="true" style="display: flex; justify-content: center; gap: 10px">
				<el-form-item style="flex-shrink: 0; width: 200px">
					<el-input v-model="name" placeholder="输入装备名称" clearable style="width: 100%" @clear="load" />
				</el-form-item>

				<el-form-item style="flex-shrink: 0; width: 180px">
					<el-select v-model="suitBelong" filterable placeholder="选择所属套装" clearable style="width: 100%" @clear="load">
						<el-option v-for="item in suitOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item style="flex-shrink: 0">
					<el-button type="primary" :icon="Search" style="min-width: 80px" @click="load"></el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<el-col style="margin-bottom: 10px; display: flex; justify-content: center">
			<el-menu :default-active="activeBelong" mode="horizontal" class="category-menu" :ellipsis="false" @select="handleMenuSelect">
				<el-menu-item index="">
					<div class="category-item">
						<span class="category-text">全部装备</span>
					</div>
				</el-menu-item>
				<el-menu-item v-for="item in belongOptions" :key="item.value" :index="item.value">
					<div class="category-item">
						<el-avatar :size="40" :src="item.icon" fit="contain"></el-avatar>
						<span class="category-text">{{ item.label }}</span>
					</div>
				</el-menu-item>
			</el-menu>
		</el-col>

		<el-col style="margin-bottom: 10px; display: flex; gap: 10px">
			<div>
				<el-button type="danger" :disabled="disabled" :icon="Operation" size="small" plain @click="handleBatchDel"> 所选装备搭配查看 </el-button>
			</div>
		</el-col>
		<!--  表格页面-->
		<el-col>
			<el-row :gutter="20" class="equip-grid" style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 20px; padding: 0 10px">
				<div v-for="(item, index) in tableData" :key="index" class="equip-grid-item">
					<el-card
						shadow="hover"
						:style="{
							border: selectedIds.includes(item.id) ? '2px solid #409EFF' : '1px solid #ebeef5',
							transform: selectedIds.includes(item.id) ? 'translateY(-3px)' : '',
							transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
						}"
						class="equip-card"
					>
						<div style="position: relative; height: 100%; display: flex; flex-direction: column" @click="handleDetail(item.id)">
							<!-- 选中状态指示 -->
							<div v-if="selectedIds.includes(item.id)" class="selected-indicator">
								<el-icon color="#409EFF" :size="24">
									<Select />
								</el-icon>
							</div>

							<!-- 图片区域 -->
							<div class="image-container">
								<el-image :src="item.img" fit="contain" class="equip-image" :preview-src-list="[item.img]" />
							</div>

							<!-- 内容区域 -->
							<div class="card-content">
								<div class="equip-name text-ellipsis">
									{{ item.name }}
								</div>

								<div class="equip-meta">
									<el-tag v-if="item.belongSuit" size="small" type="success" class="meta-tag"> 套装: {{ getSuitName(item.belongSuit) }} </el-tag>
									<el-tag size="small" class="meta-tag"> 类型: {{ getBelongLabel(item.belong) }} </el-tag>
								</div>

								<!-- 操作按钮 -->
								<div class="action-button">
									<el-button type="primary" class="full-width-btn" @click.stop="toggleSelection(item)">
										{{ selectedIds.includes(item.id) ? '取消选择' : '选择装备' }}
									</el-button>
								</div>
							</div>
						</div>
					</el-card>
				</div>
			</el-row>

			<!-- 分页 -->
			<el-col>
				<div class="pagination">
					<el-pagination
						:current-page="pageNum"
						:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
						size="small"
						layout="total, sizes, prev, pager, next, jumper"
						:total="Number(total)"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</el-col>
		</el-col>
	</el-row>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { CircleCloseFilled, Delete, Download, Edit, InfoFilled, Operation, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const name = ref('')
const activeBelong = ref('')
const belong = ref('')
const suitBelong = ref('')
const suitOptions = ref([])
const selectedIds = ref([])
const $route = router
const formSize = ref('default')
const ruleFormRef = ref()

const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	aggressivity: 0,
	critical: 0,
	defense: 0,
	mana: 0,
	fire: 0,
	ice: 0,
	drug: 0,
	thunder: 0
})

const belongOptions = ref([
	{ value: '1', label: '兵器', icon: '/public/picture/兵器.png' },
	{ value: '2', label: '葫芦', icon: '/public/picture/葫芦.png' },
	{ value: '3', label: '头冠', icon: '/public/picture/头冠.png' },
	{ value: '4', label: '臂甲', icon: '/public/picture/臂甲.png' },
	{ value: '5', label: '衣甲', icon: '/public/picture/衣甲.png' },
	{ value: '6', label: '腿甲', icon: '/public/picture/腿甲.png' },
	{ value: '7', label: '珍玩', icon: '/public/picture/珍玩.png' },
	{ value: '8', label: '精魄', icon: '/public/picture/精魄.png' }
])

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	aggressivity: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	critical: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	defense: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	mana: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	fire: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	ice: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	drug: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	thunder: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

const getSuitName = id => {
	const suit = suitOptions.value.find(item => item.id === id)
	return suit ? suit.name : '无'
}

const toggleSelection = item => {
	const index = selectedIds.value.indexOf(item.id)
	if (index > -1) {
		selectedIds.value.splice(index, 1)
	} else {
		selectedIds.value.push(item.id)
	}
	disabled.value = selectedIds.value.length === 0
}

const handleDetail = async id => {
	$route.push(`/front/equip/equipment/show?id=${id}`)
}

const getBelongLabel = value => {
	const item = belongOptions.value.find(item => item.value === value.toString())
	return item ? item.label : '未知类型'
}

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}
// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/equip/${id}`)
	Object.assign(form, res.data)
}
const handleUpdate1 = async id => {
	$route.push(`/personality?id=${id}`)
}
// 单个删除方法
const handleDel = async id => {
	await request.delete(`/equip/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

// 批量删除方法
const handleBatchDel = async () => {
	router.push(`/front/equip/detail?id=${selectedIds.value.join(',')}`)
	selectedIds.value = []
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/equip/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			belong: belong.value,
			suitId: suitBelong.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
}
// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	name.value = ''
	belong.value = ''
	suitBelong.value = ''
	activeBelong.value = ''
	load()
}
// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}
// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

const handleMenuSelect = index => {
	belong.value = index
	load()
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/equip/${form.id}` : '/equip',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/equip/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}
// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/equip/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}
// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		aggressivity: 0,
		critical: 0,
		defense: 0,
		mana: 0,
		fire: 0,
		ice: 0,
		drug: 0,
		thunder: 0
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}

onMounted(async () => {
	const res = await request.get('/suit/list')
	suitOptions.value = res.data
})
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}
.el-card {
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	border-radius: 8px;
	transition: transform 0.3s ease;

	&:hover {
		transform: scale(1.05);
	}
}

.category-menu {
	border-bottom: 2px solid #f0f0f0;
	padding: 0 20px;
	background: transparent; /* 背景透明 */
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); /* 轻微底部阴影增强层次感 */

	.el-menu-item {
		padding: 0 15px;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		position: relative; /* 用于悬停背景定位 */

		&:before {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			width: 0;
			height: 2px;
			background-color: #409eff; /* 选中时的底部指示线 */
			transition: width 0.3s ease;
		}

		&:hover {
			background-color: rgba(64, 158, 255, 0.12); /* 悬停半透明背景（比原来明显） */
			transform: translateY(-2px);
			box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15); /* 增强悬停阴影 */

			&:before {
				width: calc(100% - 30px); /* 悬停时显示底部指示线 */
				left: 15px;
			}
		}

		&.is-active {
			.category-text {
				color: #409eff;
				font-weight: 600;
			}
			.el-avatar {
				box-shadow: 0 0 0 2px #409eff;
			}
			&:before {
				width: calc(100% - 30px); /* 选中时固定指示线 */
				left: 15px;
			}
		}
	}
}

.category-item {
	display: flex;
	align-items: center;
	height: 60px; /* 统一菜单项高度 */
	padding: 0 10px;

	.el-avatar {
		margin-right: 8px;
		transition:
			transform 0.3s ease,
			box-shadow 0.3s ease;
	}

	.category-text {
		font-size: 14px;
		color: #333;
		white-space: nowrap; /* 防止文字换行 */
		transition: color 0.3s ease;
	}
}

.category-text {
	margin-top: 5px;
	font-size: 12px;
}

.el-menu-item.is-active .category-text {
	color: var(--el-color-primary);
	font-weight: bold;
}

.equip-card {
	transition: all 0.3s ease;
	cursor: pointer;
	margin: 5px;
}

.equip-card:hover {
	transform: translateY(-3px);
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.equip-name {
	font-weight: bold;
	margin: 10px 0;
	color: #333;
	font-size: 14px;
	transition: color 0.3s;
}

.equip-name:hover {
	color: #409eff;
}

.equip-info {
	margin: 8px 0;
	font-size: 12px;
	color: #666;
}

.info-item {
	margin: 4px 0;
	display: flex;
	align-items: center;
	gap: 5px;
}

.equip-stats {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 5px;
	font-size: 12px;
	color: #909399;
}

/* 网格布局适配 */
.equip-grid {
	padding-bottom: 100px; // 添加底部间距
}

.equip-grid-item {
	min-width: 0; /* 解决flex项目溢出问题 */
}

/* 卡片容器 */
.equip-card {
	height: 100%;
	border-radius: 12px;
	overflow: hidden;
	transition:
		transform 0.3s,
		box-shadow 0.3s;
}

/* 图片区域 */
.image-container {
	position: relative;
	width: 100%;
	height: 180px;
	overflow: hidden;
	border-radius: 8px 8px 0 0;
}

.equip-image {
	width: 100%;
	height: 100%;
	transition: transform 0.3s;
}

/* 内容区域 */
.card-content {
	padding: 12px;
	flex: 1;
	display: flex;
	flex-direction: column;
}

.equip-name {
	font-size: 14px;
	font-weight: 600;
	color: #303133;
	margin-bottom: 8px;
	line-height: 1.4;
}

.equip-meta {
	margin-top: auto;
	display: flex;
	flex-wrap: wrap;
	gap: 4px;
}

.meta-tag {
	margin-right: 4px;
	flex-shrink: 0;
}

/* 操作按钮 */
.action-button {
	margin-top: 12px;
}

.full-width-btn {
	width: 100%;
}

/* 选中状态指示 */
.selected-indicator {
	position: absolute;
	top: 8px;
	right: 8px;
	z-index: 2;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 50%;
	padding: 2px;
}

/* 分页容器 */
.pagination {
	position: fixed;
	bottom: 20px;
	left: 50%;
	transform: translateX(-50%);
	z-index: 1000;
	background: rgba(255, 255, 255, 0.9);
	padding: 8px 20px;
	border-radius: 24px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	display: inline-flex;

	:deep(.el-pagination__total),
	:deep(.el-pagination__jump),
	:deep(.el-pagination__sizes),
	:deep(.btn-prev),
	:deep(.btn-next) {
		color: #333;
	}

	:deep(.el-pager li) {
		color: #333;

		&.is-active {
			color: #409eff;
		}
	}
}

.text-ellipsis {
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}
</style>
